import React, { useEffect, useState } from "react";
import { Button, Divider, message, Card,Table } from "antd";
import { userList,addUser,delUser } from "../../api/user";
import AddUserForm from "./forms/addUserForms";
const { Column } = Table;

const User = () => {
    const [list,setList] = useState([]);
    const [downloadLoading,setDownloadLoading] =useState(true);
    const [addVisible,setAddVisible] = useState(false);
    const [loading,setLoading] = useState(false);
    let addUserFormRef,delUserFormRef;
    const getData = () =>{
        userList()
        .then(res => {
            let temp = res;
            let reg = new RegExp('nickName":.+","g');
            for (let i = 0; i < temp.length; i++) {
                let element = temp[i];
                // console.log(element)
                //如果用户是普通用户则让其为用户名为无
                if (element.userName == null) {
                    element.userName = '无';
                }
                let strtemp = element.userInfo.match(reg);
                //将用户的昵称提取出来;
                if (strtemp != null) {
                    let arr1 = strtemp[0].split(':');
                    let arr2 = arr1[1].split(',')
                    let strmidtemp = arr2[0].slice(1,-1);
                    // console.log(strmidtemp)
                    element.userInfo = strmidtemp;
                }
                else{
                    element.userInfo = "这是管理员账号不需要用户昵称";
                }
                let myDate = new Date(parseInt(element.userDay));
                let year = myDate.getFullYear();
                let month = myDate.getMonth()+1;
                let date = myDate.getDate();
                let h = myDate.getHours()<10?'0'+myDate.getHours():myDate.getHours();
                let m = myDate.getMinutes()<10?'0'+myDate.getMinutes():myDate.getMinutes();
                let s = myDate.getSeconds()<10?'0'+myDate.getSeconds():myDate.getSeconds();
                element.userDay= `${year}年${month}月${date}日  ${h}:${m}:${s}`
                temp[i] = element;
            }
            
            // console.log('res:',res)
            setList(res)
            // console.log('temp:',temp)
            setDownloadLoading(false)
        })
    }
    const handleAddUser = (props) => {
        // console.log(props)
        const { form } = props.props;
        form.validateFields((err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            let opt ={}
            for (const key in values) {
                opt[key] = values[key]
            };
            let date = Date.now();//创建时间
            opt.userDay=""+date;
            opt.userPrivilege = "管理员";
            opt.openId = opt.userName;
            opt.userInfo = '{"userInfo":{}}';
            // console.log(opt)
            setLoading(true)
            addUser(opt)
                .then((response) => {
                    if (response.status === 401) {
                        setLoading(false);
                        message.error("校验密码错误!");
                    }
                    else{
                        form.resetFields();
                        setAddVisible(false);
                        setLoading(false);
                        message.success("添加成功!");
                    }
                    getData();
                })
                .catch((e) => {
                    console.dir(e);
                    setLoading(false);
                    message.success('添加失败，请重试!');
                });
        });
    }
    const userDelete = (row) => {
        // console.log(row);
        // console.log(row.activityId);
        
        delUser(row.userId).then((res) => {
            if (res.status === 200) {
                message.success("删除用户成功!");
                
                // console.log(res);
            }
            else{
                message.error('删除用户失败!')
            }
            
            getData();
        });
    };
    
    const handleCancelAddUser = () => {
        setAddVisible(false);
    };
    useEffect(() => {
        getData();
    },[])
    return(
        <div>
            <Card bodyStyle={{height:64,marginBottom:0}}>
                <Button type="primary" onClick={() => {setAddVisible(true)}} style={{position:'relative',top:-5}}>
                    添加管理员用户
                </Button>
            </Card>
            <Card >
                <Table
                    bordered
                    rowKey={(record, index) => index}
                    dataSource={list}
                    loading={downloadLoading}
                    pagination={{
                        total: list.length,
                        showTotal: (total) => `共${total}条数据`,
                    }}
                    scroll={{ y: 480 }}
                    // showHeader={false}
                >
                    <Column
                        title="用户id"
                        dataIndex="userId"
                        key="userId"
                        width={80}
                        align="center"
                        sorter={(a, b) => a.userId - b.userId}
                        defaultSortOrder="descend"
                    />
                    <Column
                        title="openID"
                        dataIndex="openId"
                        key="openId"
                        width={100}
                        align="center"
                    />
                    <Column
                        title="用户昵称"
                        dataIndex="userInfo"
                        key="fullTitle"
                        width={100}
                        align="center"
                    />
                    <Column
                        title="用户创建日期"
                        dataIndex="userDay"
                        key="userDay"
                        width={120}
                        align="center"
                    />
                    <Column
                        title="用户身份"
                        dataIndex="userPrivilege"
                        key="userPrivilege"
                        width={90}
                        align="center"
                    />
                    <Column
                        title="用户名(仅用于管理员账号)"
                        dataIndex="userName"
                        key="userName"
                        width={140}
                        align="center"
                    />
                    <Column
                        title="操作"
                        key="action"
                        width={120}
                        align="center"
                        render={(text, row) => (
                            <span>
                                <Button
                                    type="primary"
                                    shape="circle"
                                    icon="delete"
                                    title="删除"
                                    onClick={() => {userDelete(row)}}
                                />
                            </span>
                        )}
                    />
                </Table>
            </Card>
            <AddUserForm
                wrappedComponentRef={(formRef) => {addUserFormRef=formRef}}
                visible={addVisible}
                confirmLoading={loading}
                onCancel={handleCancelAddUser}
                onOk={() => {handleAddUser(addUserFormRef)}}
            />
            
        </div>
    );
};

export default User;
